package com.jaydenxiao.common.manager;

import android.util.Log;

import com.jaydenxiao.common.baseapp.BaseApplication;
import com.jaydenxiao.common.commonutils.NetWorkUtils;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.jaydenxiao.common.token.TokenUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 功能： 在有网络的情况下，先去读缓存，设置的缓存时间到了，在去网络获取
 * 描述
 * Created by yue on 2019-07-02
 */
public class NetInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        request = request.newBuilder()
                .header("Connection", "close")
                .header("Accept", "application/json")
                .header("Authorization", TokenUtil.getAuthorization())
                .header("Content-Type", "application/json")
                .build();

        boolean connected = NetWorkUtils.isNetConnected(BaseApplication.getAppContext());
        if (connected) {
            //如果有网络，缓存90s
            Log.e("zhanghe", "print");
            Log.e("request", request.toString());
            Response response = chain.proceed(request);
            int maxTime = 90;
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .header("Connection", "close")
                    .header("Cache-Control", "public, max-age=" + maxTime)
                    .build();
        }
        //如果没有网络，不做处理，直接返回
        return chain.proceed(request);
    }
}